﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MyBlog.Model;
using MyBlog.Common;
using System.Threading.Tasks;

namespace MyBlog
{
    /// <summary>
    /// 应用程序缓存处理类
    /// </summary>
    public static class WebCache
    {
        /// <summary>
        /// 用户集合缓存
        /// </summary>
        public static List<AccountModel> UsersCache = new List<AccountModel>();
        //{
        //    private set { }
        //    get
        //    {
        //        var cache = HttpRuntime.Cache["XiaoBoKe_UsersCache"] as List<AccountModel> ?? new List<AccountModel>();
        //        return cache;
        //    }
        //}

        /// <summary>
        /// 获取系统是否开启匿名操作
        /// </summary>
        public static bool AllowAnonymous
        {
            get
            {
                if (System.Configuration.ConfigurationManager.AppSettings["AllowAnonymous"].ToString().Trim() == "true")
                {
                    return true;
                }
                return false;
            }
        }

        /// <summary>
        /// 获取系统邮箱地址
        /// </summary>
        public static string SystemMail
        {
            get
            {
                if (System.Configuration.ConfigurationManager.AppSettings["systemMail"] != null)
                {
                    return System.Configuration.ConfigurationManager.AppSettings["systemMail"].ToString().Trim();
                }
                return "";
            }
        }

        /// <summary>
        /// 获取系统主机域名地址
        /// </summary>
        public static string SystemHost
        {
            get
            {
                if (System.Configuration.ConfigurationManager.AppSettings["systemHost"] != null)
                {
                    return System.Configuration.ConfigurationManager.AppSettings["systemHost"].ToString().Trim();
                }
                return "";
            }
        }

        /// <summary>
        /// 获取是否设置一直使用邮件发送通知
        /// </summary>
        public static bool IsAlwaysSendMail
        {
            get
            {
                if (System.Configuration.ConfigurationManager.AppSettings["IsAlwaysSendMail"].ToString().Trim() == "true")
                {
                    return true;
                }
                return false;
            }
        }

        /// <summary>
        /// 获取系统是否设置需要激活才能登录
        /// </summary>
        public static bool NeedActive
        {
            get
            {
                if (System.Configuration.ConfigurationManager.AppSettings["NeedActive"].ToString().Trim() == "true")
                {
                    return true;
                }
                return false;
            }
        }

        public static int CacheTimeout
        {
            get
            {
                if (!string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["CacheTimeout"].ToString().Trim()))
                {
                    return int.Parse(System.Configuration.ConfigurationManager.AppSettings["CacheTimeout"].ToString().Trim());
                }
                return 0;
            }
        }

        /// <summary>
        /// 获取所有用户信息，去除密码等敏感信息
        /// </summary>
        /// <returns></returns>
        private static List<AccountModel> GetAllUsers()
        {
            var users = XiaoBoKe.AccountService.GetAll();
            users.ForEach(x => x.Password = null);
            return users;
        }

        /// <summary>
        /// 初始化应用程序缓存，在应用程序启动时执行
        /// </summary>
        public static void InitCache()
        {
            try
            {
                HttpRuntime.Cache["XiaoBoKe_UsersCache"] = UsersCache = GetAllUsers();
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("初始化用户缓存失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 刷新用户缓存信息
        /// </summary>
        /// <param name="isAll">是否刷新全部，默认false</param>
        public static void Refresh(bool isAll = false, params string[] uids)
        {
            try
            {
                if (isAll)
                {
                    HttpRuntime.Cache["XiaoBoKe_UsersCache"] = UsersCache = GetAllUsers();
                    return;
                }
                var accountList = uids.Length == 0 ? new string[] { UserSession.AccountId } : uids;
                foreach (var item in accountList)
                {
                    UsersCache.RemoveAll(x => x.Account.Same(item));
                    var userNew = XiaoBoKe.AccountService.Get(item);
                    userNew.Password = null;
                    UsersCache.Add(userNew);
                }
                HttpRuntime.Cache["XiaoBoKe_UsersCache"] = UsersCache;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("刷新用户缓存失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 在缓存中读取用户信息
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public static AccountModel GetAccount(string account)
        {
            var cacheUser = UsersCache.FirstOrDefault(x => x.Account.Same(account));
            if (null == cacheUser)
            {
                cacheUser = XiaoBoKe.AccountService.Get(account);
            }
            return cacheUser;
        }

        /// <summary>
        /// 在缓存中获取用户昵称
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public static string GetNickName(string account)
        {
            return GetAccount(account).NickName;
        }

        /// <summary>
        /// 在缓存中读取用户类别列表
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public static List<CategoryModel> GetCategories(string account)
        {
            List<CategoryModel> models = new List<CategoryModel>();
            if (!string.IsNullOrWhiteSpace(account))
            {
                var user = UsersCache.FirstOrDefault(x => x.Account.Same(account));
                if (user != null)
                {
                    models = user.CategoryModels;
                }
            }
            else
            {
                UsersCache.ForEach(x => models.AddRange(x.CategoryModels));
            }
            return models;
        }

        /// <summary>
        /// 在缓存中读取用户标签列表
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public static List<TagModel> GetTags(string account = null)
        {
            List<TagModel> models = new List<TagModel>();
            if (!string.IsNullOrWhiteSpace(account))
            {
                var user = UsersCache.FirstOrDefault(x => x.Account.Same(account));
                if (user != null)
                {
                    models = user.TagModels;
                }
            }
            else
            {
                UsersCache.ForEach(x => models.AddRange(x.TagModels));
            }
            return models;
        }

        /// <summary>
        /// 在缓存中获取用户文章列表
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public static List<ArticleModel> GetArticles(string account = null)
        {
            List<ArticleModel> models = new List<ArticleModel>();
            if (!string.IsNullOrWhiteSpace(account))
            {
                var user = UsersCache.FirstOrDefault(x => x.Account.Same(account));
                if (user != null)
                {
                    models = user.ArticleModels;
                }
            }
            else
            {
                UsersCache.ForEach(x => models.AddRange(x.ArticleModels));
            }
            return models;
        }

        /// <summary>
        /// 在缓存中获取文章上一篇和下一篇
        /// </summary>
        /// <param name="account"></param>
        /// <param name="aid"></param>
        /// <returns></returns>
        public static List<Tuple<int, string>> GetArticlePrevAndNext(string account, int aid)
        {
            var all = GetArticles(account);
            var result = new List<Tuple<int, string>>();
            var curr = all.First(x => x.ID == aid);
            if (all.Count > 1)
            {
                //方法1：需要id从小到大排序
                all = all.OrderBy(x => x.ID).ToList();
                var prev = all.Where(x => x.ID < aid).LastOrDefault() ?? new ArticleModel();
                var next = all.Where(x => x.ID > aid).FirstOrDefault() ?? new ArticleModel();
                //方法2：不需要排序
                //var prev = (from p in all where aid > p.ID && p.ID == all.Where(x => x.ID < aid).Max(x => x.ID) select p).FirstOrDefault() ?? new ArticleModel();
                //var next = (from p in all where aid < p.ID && p.ID == all.Where(x => x.ID > aid).Min(x => x.ID) select p).FirstOrDefault() ?? new ArticleModel();
                result.Add(new Tuple<int, string>(prev.ID, prev.Title));
                result.Add(new Tuple<int, string>(next.ID, next.Title));
            }
            return result;
        }

        /// <summary>
        /// 在缓存中获取某用户关注的人
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public static List<ConcernModel> GetMyConcernUsers(string account)
        {
            List<ConcernModel> models = new List<ConcernModel>();
            if (!string.IsNullOrWhiteSpace(account))
            {
                var user = UsersCache.FirstOrDefault(x => x.Account.Same(account));
                if (user != null)
                {
                    user.MyConcernUsers.ForEach(x => x.ConcernUser = x.ConcernUser ?? WebCache.GetAccount(x.ConcernUID));
                    models = user.MyConcernUsers;
                }
            }
            else
            {
                UsersCache.ForEach(x => models.AddRange(x.MyConcernUsers));
            }
            return models;
        }

        /// <summary>
        /// 在缓存中获取关注该用户的人
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public static List<ConcernModel> GetConcernMeUsers(string account)
        {
            List<ConcernModel> models = new List<ConcernModel>();
            if (!string.IsNullOrWhiteSpace(account))
            {
                var user = UsersCache.FirstOrDefault(x => x.Account.Same(account));
                if (user != null)
                {
                    user.ConcernMeUsers.ForEach(x => x.Account = x.Account ?? WebCache.GetAccount(x.UID));
                    models = user.ConcernMeUsers;
                }
            }
            else
            {
                UsersCache.ForEach(x => models.AddRange(x.ConcernMeUsers));
            }
            return models;
        }

        /// <summary>
        /// 在缓存中获取用户通知消息
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public static List<NoticeModel> GetMyNotices(string account)
        {
            List<NoticeModel> models = new List<NoticeModel>();
            if (!string.IsNullOrWhiteSpace(account))
            {
                var user = UsersCache.FirstOrDefault(x => x.Account.Same(account));
                if (user != null)
                {
                    models = user.MyNotices;
                }
            }
            else
            {
                UsersCache.ForEach(x => models.AddRange(x.MyNotices));
            }
            return models;
        }

        /// <summary>
        /// 生成激活码
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public static string CreateActiveCode(string uid)
        {
            var code = new Random().Next(100000, 999999).ToString();
            return code;
        }
    }
}